# coding=utf-8

import web
import json
from monkey import get_connected_devices, get_device_model, getpackageinfoindevice, execlinemonkey, get_devices_has_state


urls = (
	'/(.*)', 'controller'
)

class controller:

	def POST(self, path):
		web.header("Access-Control-Allow-Origin", "*")
		data = web.data()
		print data
		execlinemonkey(json.loads(data))
		return "1"
	
	def GET(self, path):
		web.header("Access-Control-Allow-Origin", "*")
		print "path---", path
		# print web.ctx.fullpath
		if not path:
			path = 'pages/settings.html'
		elif path == 'favicon.ico':
			return ""
		elif path == 'getdevices':
			devices = get_devices_has_state()
			# print json.dumps(devices)
			return json.dumps(devices)
		elif 'getpackagesindevice' == path: 
			devicesn = web.input().device
			pkginfo = getpackageinfoindevice(devicesn)
			print pkginfo
			return json.dumps(pkginfo)
		# print "path---", path
		try:
			import os
			print os.path.abspath(".")
			return open('./monkeysettings/' + path).read()
		except IOError, e:
			print e.message
			# return open('./monkeysettings/error/500.html').read()

if __name__ == '__main__':
	app = web.application(urls, globals())
	app.run()